package org.example.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.EnumResolver;
import jdk.nashorn.internal.runtime.ECMAException;
import org.example.JDBC.Select;
import org.example.User.User;
import org.example.User.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sound.sampled.Line;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.Enumeration;

@WebServlet("/blog_login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            UserDao userDao = new UserDao();
            User user = userDao.selectByName(username);
            if ("".equals(username) || "".equals(password) || !user.getUserName().equals(username) || !user.getUserPassword().equals(password)) {
                RespInfo respInfo = new RespInfo();
                respInfo.setStatus(0);
                respInfo.setContent("用户名或密码错误");
                resp.setContentType("application/json;charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                resp.getWriter().write(objectMapper.writeValueAsString(respInfo));
                return;
            }
            resp.setStatus(302);
            resp.sendRedirect("blog_list.html");
            System.out.println("后端处理请求进行验证");
            return ;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

class UserInfo {
    public String username;

    public String getUserName() {
        return username;
    }

    public void setUserName(String userName) {
        this.username = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String password;
}

class RespInfo {
    private int status;
    private String content;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}